<template>
  <div>
    <!-- 面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域-->
    <el-card class="box-card">
      <el-row>
        <!-- :gutter="10"-->
        <el-col :span="7">
          <!-- 搜索添加区域-->
          <el-input placeholder="请输入用户" v-model='queryInfo.query' :clearable='true' @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click='getUserList'></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click='addUser'>添加用户</el-button>
        </el-col>
      </el-row>

      <!--用户列表区域-->
      <el-table :data="userlist" :border="true" :stripe="true"
        :header-cell-style="{'text-align':'center','font-weight':'700','color':'#606266'}"
        :cell-style="{'text-align':'center'}">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="UserId" v-if='false'></el-table-column>
        <el-table-column label="姓名" prop="UserName"></el-table-column>
        <el-table-column label="邮箱" prop="Email"></el-table-column>
        <el-table-column label="电话" prop="Moblie"></el-table-column>
        <el-table-column label="角色" prop="RoleName"></el-table-column>
        <el-table-column label="创建时间" prop="CreateTime" :formatter="dateFormat"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- slot-scope="scope"获取当前行  -->
            <!-- {{scope.row.Mg_State}} -->
            <el-switch v-model="scope.row.Mg_State" active-color="#13ce66" inactive-color="#ff4949"
              @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px;">
          <template slot-scope="scope">
            <!--修改-->
            <el-tooltip content="修改用户" placement="bottom" effect="light" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.UserId)">
              </el-button>
            </el-tooltip>

            <!--删除-->
            <el-tooltip content="删除用户" placement="bottom" effect="light" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.UserId)">
              </el-button>
            </el-tooltip>

            <!--分配角色-->
            <el-tooltip content="分配角色" placement="bottom" effect="light" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" background>
      </el-pagination>
    </el-card>

    <el-dialog title='添加用户' :visible.sync="addDialogVisible" width="50%" @closed='addUserFormClosed'>
      <!--内容主体区-->
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width='100px'>
        <el-form-item label='用户名' prop='UserName'>
          <el-input v-model='addUserForm.UserName'></el-input>
        </el-form-item>
        <el-form-item label='密码' prop='Password'>
          <el-input type='password' v-model='addUserForm.Password' :show-password="true"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="Password_confirm">
          <el-input type="password" v-model="addUserForm.Password_confirm" :show-password="true">
          </el-input>
        </el-form-item>
        <el-form-item label='邮箱' prop='Email'>
          <el-input v-model='addUserForm.Email'></el-input>
        </el-form-item>
        <el-form-item label='手机' prop='Moblie'>
          <el-input v-model='addUserForm.Moblie'></el-input>
        </el-form-item>
        <el-form-item label='是否启用' prop='Mg_State'>
          <el-switch v-model="addUserForm.Mg_State" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
      </el-form>
      <!--底部区-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserContent">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @closed="editUserFormClosed"
      :close-on-click-modal="false">
      <!--修改用户内容主体区-->
      <el-form :model="editUserForm" :rules="addUserFormRules" ref="editUserFormRef" label-width='100px'>
        <el-form-item label='用户ID' v-if='false'>
          <el-input v-model='editUserForm.UserId'></el-input>
        </el-form-item>
        <el-form-item label='用户名'>
          <el-input v-model='editUserForm.UserName' disabled></el-input>
        </el-form-item>
        <el-form-item label='角色' prop='RoleName'>
          <el-input v-model='editUserForm.RoleName'></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="Email">
          <el-input v-model='editUserForm.Email'></el-input>
        </el-form-item>
        <el-form-item label='手机' prop='Moblie'>
          <el-input v-model='editUserForm.Moblie'></el-input>
        </el-form-item>
        <el-form-item label='是否启用' prop='Mg_State'>
          <el-switch v-model="editUserForm.Mg_State" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.addUserForm.Password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }

      const validatePhone = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('手机号不能为空'))
        } else if (!(/^1[34578]\d{9}$/.test(value))) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }

      const validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('邮箱不能为空'))
        } else if (!(/^[a-zA-Z0-9]+([._\\-]*[a-zA-Z0-9])*@([a-zA-Z0-9]+[-a-zA-Z0-9]*[a-zA-Z0-9]+.){1,63}[a-zA-Z0-9]+$/
            .test(value))) {
          callback(new Error('请输入正确的邮箱号'))
        } else {
          callback()
        }
      }

      return {
        // 获取用户列表的参数对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },
        userlist: [],
        total: 0,
        addDialogVisible: false, // 控制是否显示新增用户的dialog
        addUserForm: {
          UserName: '',
          Password: '',
          Password_confirm: '',
          Email: '',
          Moblie: '',
          Mg_State: true
        },
        editDialogVisible: false, // 控制是否显示修改用户的dialog
        editUserForm: {
          UserId: '',
          UserName: '',
          RoleName: '',
          CreateTime: '',
          Mg_State: false,
          Email: '',
          Moblie: ''
        },
        // 添加表单应用规则
        addUserFormRules: {
          UserName: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '用户名长度在3-10之间',
              trigger: 'blur'
            }
          ],
          Password: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{6,15}$/,
              message: '密码为数字，小写字母，大写字母，特殊符号 至少包含三种，长度为 6 - 15位',
              trigger: 'blur'
            }
          ],
          Password_confirm: [{
            required: true,
            validator: validatePass,
            trigger: 'blur'
          }],
          Email: [{
            required: true,
            validator: validateEmail,
            trigger: 'blur'
          }],
          Moblie: [{
            validator: validatePhone,
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        const {
          data: res
        } = await
        this.$http.get('/Login/UserInfo/SearchUserList', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取用户列表失败')
        }
        this.$message.success('获取用户列表成功')
        this.userlist = res.data.users
        this.total = res.data.total
      },
      // 监听pageSize改变的事件
      handleSizeChange(val) {
        this.queryInfo.pagesize = val
        this.getUserList()
        console.log(`每页 ${val} 条`)
      },
      // 监听页码值改变事件
      handleCurrentChange(val) {
        this.queryInfo.pagenum = val
        this.getUserList()
        console.log(`当前页: ${val}`)
      },
      // 监听switch的行为状态
      async userStateChange(userInfo) {
        console.log(userInfo)
        const {
          data: res
        } = await
        this.$http.put('/Login/UserInfo/SaveUserCurrentState', userInfo)
        if (res.meta.status === 200) {
          this.$message.success(`修改用户${userInfo.UserName}成功`)
        } else {
          userInfo.Mg_State = !userInfo.Mg_State
          this.$message.error(`修改用户${userInfo.UserName}失败`)
        }
      },
      // 打开弹出框
      addUser() {
        this.addDialogVisible = true
      },
      // 用户信息保存到数据库中
      addUserContent() {
        this.$refs.addUserFormRef.validate(async valid => {
          if (!valid) {
            return
          }
          const {
            data: res
          } = await this.$http.post('/Login/UserInfo/InsertUserInfo', this.addUserForm)
          if (res.meta.status !== 200) {
            // 添加用户失败
            return this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUserList()
        })
      },
      // 关闭弹出框后重置弹出框中的form内容
      addUserFormClosed() {
        this.$refs.addUserFormRef.resetFields()
      },
      // 关闭修改用户弹出框后重置弹出框中的form内容
      editUserFormClosed() {
        this.$refs.editUserFormRef.resetFields()
      },
      // 展示修改用户对话框
      async showEditDialog(obj) {
        console.log(obj)
        // 从后台捞取对应的用户信息
        const {
          data: res
        } = await this.$http.get('/Login/UserInfo/SelectUserById', {
          params: {
            UserId: obj
          }
        })
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('查询用户数据失败')
          return
        }
        // 查询到数据,打开弹出框
        this.editUserForm = res.data.user
        this.editDialogVisible = true
      },
      // 监听修改用户对话框关闭
      editDialogClosed() {
        this.$refs.editUserFormRef.resetFields()
        this.editDialogVisible = false
      },
      editUserInfo() {
        this.$refs.editUserFormRef.validate(async valid => {
          console.log(valid)
          if (!valid) {
            return
          }
          // 发生请求修改参数
          const {
            data: res
          } = await this.$http.post('/Login/UserInfo/UpdateUserInfo', this.editUserForm)
          if (res.meta.status !== 200) {
            this.$message.error('修改用户数据失败')
            return
          }
          this.$message.success('修改用户成功')
          this.editDialogVisible = false
          this.getUserList()
        })
      },
      // 删除用户
      deleteUser(obj) {
        console.log(this.$store)
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async () => {
          // 后台删除
          const {
            data: res
          } = await
          this.$http.delete('/Login/UserInfo/DeleteUserInfo', {
            params: {
              UserId: obj
            }
          })
          if (res.meta.status !== 200) {
            this.$message.error('删除用户数据失败')
            return
          }
          // 更新用户列表
          this.$message.success('删除用户数据成功')
          this.getUserList()
        }).catch(() => {
          this.$message.info('取消删除')
        })
      },
      // 修改时间格式
      dateFormat(row, column, cellValue, index) {
        const daterc = row[column.property]
        if (daterc != null) {
          const dateMat = new Date(daterc) // parseInt(daterc.replace('/Date(', '').replace(')/', ''), 10)
          const year = dateMat.getFullYear()
          const month = dateMat.getMonth() + 1
          const day = dateMat.getDate()
          const hh = dateMat.getHours()
          const mm = dateMat.getMinutes()
          const ss = dateMat.getSeconds()
          const timeFormat = year + '-' + month.toString().PadLeft(2, '0') + '-' + day.toString().PadLeft(2, '0') +
            ' ' + hh.toString().PadLeft(2, '0') + ':' + mm.toString()
            .PadLeft(2, '0') + ':' + ss.toString().PadLeft(2, '0')
          return timeFormat
        }
      }
    }
  }

</script>

<style lang="less" scoped>
  /deep/ .el-form-item__content:last-child {
    text-align: left;
  }

</style>
